package qeug.shsh.facde.controller;

import com.drew.lang.annotations.NotNull;
import com.huawei.shade.org.apache.commons.logging.Log;
import com.huawei.shade.org.apache.commons.logging.LogFactory;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.param.AppCustomParam;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.custom.annotation.ApiRequestBody;
import kd.bos.openapi.common.custom.annotation.ApiResponseBody;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.org.api.IOrgService;
import kd.bos.org.model.OrgParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.service.ServiceFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import qeug.shsh.facde.RequestContextService;
import qeug.shsh.facde.info.IAMOrgModel;
import qeug.shsh.facde.info.UserModel;
import qeug.shsh.facde.resultext.UserResultExt;
import qeug.shsh.helper.FacadeHelper;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@ApiController(value = "IAMOrgController", desc = "金蝶IAM同步组织接口，自定义插件")
public class IAMOrgController {

    private final static Log logger = LogFactory.getLog(IAMOrgController.class);//日志

    static CustomApiResult auditApiResultExt = new CustomApiResult();

    static UserResultExt userResultExt = new UserResultExt();

    @ApiPostMapping(value = "/shsh_iamOrg", desc = "组织许可api接口")
    public CustomApiResult<@ApiResponseBody("返回参数") UserResultExt> resultExt
            (@NotNull @ApiRequestBody(value = "入参") IAMOrgModel model) throws ParseException {

        //根据应用编码从缓存中获取应用信息
        AppInfo cgfwAppInfo = AppMetadataCache.getAppInfo("basedata");
        //获取应用的主键
        String appId = cgfwAppInfo.getId();
        AppCustomParam appCustomParam = new AppCustomParam(appId);
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadAppCustomParameterFromCache(appCustomParam);
        boolean action = true;
        for (String value : cusTomMap.values()) {
            if (!value.equals("true")){
                userResultExt.setMsg("组织接口调用失败，错误原因：CCS暂未开启接受IAM组织参数");
                userResultExt.setData("");
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("400");
                return CustomApiResult.success(userResultExt);
            }
        }
        RequestContext context = RequestContext.get();
        QFilter filter = new QFilter("name", QCP.equals, "文艺雄");//过滤条件
        DynamicObject userObj = QueryServiceHelper.queryOne("bos_user","id,name", new QFilter[]{filter});
        RequestContext.copyAndSet(RequestContextService.copy(context, userObj.getString("id")));

        String name = model.getName();//部门名称
        String code = model.getCode();//部门编码
        String parentCode = model.getParentCode();//上级部门编码
        String status = model.getStatus();//状态
        String createTime = model.getCreateTime();//创建时间
        String updateTime = model.getUpdateTime();//更新时间
        String type = model.getType();//类型

        DynamicObject adminOrg = BusinessDataServiceHelper.
                loadSingle("bos_adminorg", new QFilter("number", "=", code).toArray());
        if (adminOrg == null) {
            //组织编码在组织中未找到，新增组织
            List<OrgParam> paramList = new ArrayList<>();
            // 新增单个视图方案的组织
            OrgParam param = new OrgParam();
            DynamicObject parent = BusinessDataServiceHelper.
                    loadSingle("bos_adminorg", new QFilter("number", "=", parentCode).toArray());
            param.setName(name);//组织名称
            param.setNumber(code);//组织编码
            param.setOrgPatternId(4L);//公司
            if ("1".equals(type)) {
//                param.setOrgPatternId(7L);//集团
                parent = BusinessDataServiceHelper.
                        loadSingle("bos_adminorg", new QFilter("number", "=", "5100").toArray());
                param.setParentId(parent.getLong("id"));//上级组织
            } else{
                if(parent==null){
                    userResultExt.setMsg("组织接口调用失败，错误原因：上级部门未找到！");
                    userResultExt.setData(code);
                    userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                    userResultExt.setCode("400");
                    return CustomApiResult.success(userResultExt);
                }
                param.setParentId(parent.getLong("id"));//上级组织
            }//组织类型
            param.setDuty(OrgViewType.Admin);

            // 设置组织属性
            Map<String, Object> proMap = new HashMap<>();
            if ("1".equals(status)) {
                proMap.put("enable", "1");//启用
                proMap.put("status", "C");//已审核
            } else if ("2".equals(status)) {
                proMap.put("enable", "0");//停用
                proMap.put("status", "A");//暂存
            }//状态
            param.setPropertyMap(proMap);
            paramList.add(param);
            // 业务调用可以参照接口名，以下举例说明微服务调用方式
            IOrgService orgService = ServiceFactory.getService(IOrgService.class);
            orgService.addOrUpdate(paramList);
            //orgService.update(paramList);
            System.out.println();
            // 判断执行结果
            for (OrgParam result : paramList) {
                if (!Objects.equals(result.getMsg(), "")) {
                    //错误
                    userResultExt.setMsg("组织接口调用失败，错误原因：" + result.getMsg());
                    userResultExt.setData(result.getMsg());
                    userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                    userResultExt.setCode("400");
                } else {
                    //成功
                    userResultExt.setMsg("组织接口调用成功");
                    userResultExt.setData(param.getNumber()+param.getName());
                    userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                    userResultExt.setCode("0");
                }
            }
        }else {
            //修改组织数据
            DynamicObject parent = BusinessDataServiceHelper.
                    loadSingle("bos_adminorg", new QFilter("number", "=", parentCode).toArray());
            if(parent==null && !type.equals("1")){
                userResultExt.setMsg("组织接口调用失败，错误原因：上级部门未找到！");
                userResultExt.setData(code);
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("400");
                return CustomApiResult.success(userResultExt);
            }
            adminOrg.set("orgpattern", parent);
            if ("1".equals(status)) {
                adminOrg.set("enable", "1");//启用//使用状态
                adminOrg.set("status", "C");//已审核//数据状态
            } else if ("2".equals(status)) {
                adminOrg.set("enable", "0");//停用//使用状态
                adminOrg.set("status", "A");//暂存//数据状态
            }
//            if(adminOrg.getDynamicObject("orgpattern")==null){
//                adminOrg.set("orgpattern",FacadeHelper.getDynamicObject("bos_org_pattern","name","部门"));
//            }
            adminOrg.set("name",name);
            adminOrg.set("number",code);
            adminOrg.set("createTime",new SimpleDateFormat("yyyy-MM-dd").parse(createTime));
            adminOrg.set("modifytime",new SimpleDateFormat("yyyy-MM-dd").parse(updateTime));
//            List<OrgParam> orgList = new ArrayList<>();
//            orgList.add(adminOrg);
//            OrgUnitServiceHelper.addOrUpdate(orgList);
            OperationResult bos_adminorg = SaveServiceHelper.saveOperate("bos_adminorg", new DynamicObject[]{adminOrg}, OperateOption.create());//新增、修改
            if (bos_adminorg.isSuccess()) {
                //成功
                userResultExt.setMsg("组织接口调用成功");
                userResultExt.setData("");
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("0");
            }else{
                //错误
                userResultExt.setMsg("组织接口调用失败，错误原因：" + bos_adminorg.getMessage());
                userResultExt.setData(bos_adminorg.getMessage());
                userResultExt.setTimestamp(new Timestamp(new Date().getTime()).toString());
                userResultExt.setCode("400");
            }
        }
        return CustomApiResult.success(userResultExt);
    }
        }
